package client;

import java.util.Properties;

import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

import job.Job;

public class JMSClient {
	
	private static final int DEFAULT_JOBS_NUM = 100;
	
	
	public static void main(String[] args) {
		try {
			Properties properties = new Properties();
			properties.put("java.naming.factory.initial", "fr.dyade.aaa.jndi2.client.NamingContextFactory");
			properties.put("java.naming.factory.host", "localhost");
			properties.put("java.naming.factory.port", "16400");
			Context ictx = new InitialContext(properties);
			
			Queue queue = (Queue) ictx.lookup("queue");
			QueueConnectionFactory qcf = (QueueConnectionFactory) ictx.lookup("qcf");
			ictx.close();
		
			QueueConnection qc = qcf.createQueueConnection();
			QueueSession qs = qc.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
			QueueSender qsend = qs.createSender(queue);
			ObjectMessage msg = qs.createObjectMessage();
			Queue tempQueue = qs.createTemporaryQueue();
			msg.setJMSReplyTo(tempQueue);
			QueueReceiver qrec = qs.createReceiver(tempQueue);

			qc.start();
			
			int n;
			try {
				n = (args.length>=1)? Integer.parseInt(args[0]) : DEFAULT_JOBS_NUM;
			} catch (Exception e) {
				System.out.println("ERROR: incorrect input, " + DEFAULT_JOBS_NUM + " messages will be sent");
				n = DEFAULT_JOBS_NUM;
			}
			
			String name = (args.length==2)? args[1] : "J";
			
			Job job;
			
			for(int i=0; i<n; i++) {
				System.out.println("Sending requests "+name+i);
				msg.setObject(new Job(name+i));
				qsend.send(msg);
			}
			
			System.out.println("\nWaiting for replies ...\n");
			
			for(int i=n; i>0; i--) {
				ObjectMessage reply = (ObjectMessage) qrec.receive();
				job = (Job) reply.getObject();
				System.out.println("Reply of "+ job.getName() +" received: " + job.getResult());
			}
		
			qc.close();
		} catch(Exception e) {
			System.out.println("ERROR: "+e.getMessage());
			e.printStackTrace();
		}
		
    }

}
